<?php
/***********************************************strat商品API***************************************************/
 	/**
	 * taobao.items.get:搜索商品信息（返回值没有ItemCategory）  [查] 
	 **/
	 function TOP_ItemsGet($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,itemsGet); 
	 }
 	/**
	 * taobao.items.search:搜索商品全部信息（返回值有ItemCategory） [查]  
	 **/
	 function TOP_ItemsSearch($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,itemsSearch); 
	 }
	/**
	 * taobao.items.onsale.get :得到当前会话用户出售中的商品列表  [买] 
	 **/
	 function TOP_ItemsOnsaleGet($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,itemsOnsaleGet,'item'); 
	 }
	/**
	 * taobao.items.inventory.get:得到当前会话用户库存中的商品列表  [卖]
	 *  
	 **/
	 function TOP_ItemsInventoryGet($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,itemsInventoryGet,'item'); 
	 }
	/**
	 * taobao.items.all.get :得到当前会话用户的商品列表给      [卖]
	 *  
	 **/
	 function TOP_ItemsAllGet($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,itemsAllGet,'item'); 
	 }
   /**
	 * taobao.item.get :得到单个商品信息      [查]
	 *  
	 **/
	 function TOP_ItemGet($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);   
	    return returnCallBackPage($client,itemGet); 
	 }
	/**
	 * taobao.item.update:更新商品信息      [卖]
	 *  
	 **/
	 function TOP_ItemUpdate($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,itemUpdate); 
	 }
	 /**
	 * taobao.item.add :添加一个商品        [卖]
	 *  
	 **/
	 function TOP_ItemAdd($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,itemAdd); 
	 }
	/**
	 * taobao.item.img.upload :添加商品图片    [卖]
	 *  
	 **/
	 function TOP_ItemImgUpload($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,itemImgUpload); 
	 } 
	/**
	 *  taobao.item.img.delete :删除商品图片  [卖]
	 **/
	 function TOP_ItemImgDelete ($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,itemImgDelete ); 
	 }
	 /**
	 *  taobao.item.propimg.delete :删除属性图片   [卖]
	 **/
	 function TOP_ItemPropimgDelete ($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,itemPropimgDelete ); 
	 }
	/**
	 *  taobao.item.propimg.upload :添加或修改属性图片   [卖]
	 **/
	 function TOP_ItemPropimgUpload ($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,itemPropimgUpload ); 
	 } 
	/**
	 *  taobao.item.sku.add :添加SKU    [卖]
	 **/
	 function TOP_ItemSkuAdd ($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,itemSkuAdd ); 
	 } 
	/**
	 * taobao.item.sku.get :获取SKU  [查]
	 **/
	 function TOP_ItemSkuGet ($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,itemSkuGet ); 
	 } 
	/**
	 *  taobao.item.sku.update :更新SKU信息  [卖]
	 **/
	 function TOP_ItemSkuUpdate ($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,itemSkuUpdate ); 
	 } 
	/**
	 * taobao.item.skus.get :根据卖家昵称和商品ID列表获取SKU信息 [查]
	 **/
	 function TOP_ItemSkusGet ($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,itemSkusGet ); 
	 } 
	 /**
	 *  taobao.item.update.delisting :商品下架    [高]
	 **/
	 function TOP_ItemUpdateDelisting ($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client, itemUpdateDelisting); 
	 }
	 /**
	 * taobao.item.update.listing :一口价商品上架  [高]
	 **/
	 function TOP_ItemUpdateListing ($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client, itemUpdateListing ); 
	 }
	 /**
	 *   taobao.postages.get:获取卖家的运费模板   [卖]
	 **/
	 function TOP_PostagesGet ($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,postagesGet ); 
	 }
	 /**
	 *  taobao.postage.add:添加邮费模板    [卖]
	 **/
	 function TOP_PostageAdd ($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,postageAdd ); 
	 }
	 /**
	 *  taobao.postage.update:修改邮费模板   [商]
	 **/
	 function TOP_PostageUpdate ($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,postageUpdate); 
	 }
	 /**
	 *  taobao.postage.get:获取单个运费模板  [卖]
	 **/
	 function TOP_PostageGet ($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,postageGet ); 
	 }
	 /**
	 *  taobao.postage.delete:删除邮费模板   [商]
	 **/
	 function TOP_PostageDelete ($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,postageDelete ); 
	 }
	 /**
	 *  taobao.items.custom.get:根据外部ID取商品   [商] 
	 **/
	 function TOP_ItemsCustomGet ($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,itemsCustomGet ); 
	 }
	 /**
	 * taobao.skus.custom.get:根据外部ID取商品SKU   [商]
	 **/
	 function TOP_SkusCustomGet ($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,skusCustomGet ); 
	 }
	 /**
	 *  taobao.item.recommend.delete :取消橱窗推荐一个商品  [高]
	 **/
	 function TOP_ItemRecommendDelete ($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,itemRecommendDelete ); 
	 }
	 /**
	 *  taobao.item.recommend.add :橱窗推荐一个商品   [高]
	 **/
	 function TOP_ItemRecommendAdd ($userParamArr){
	    $client = new Client();  
	    setUserParameter($client,$userParamArr);  
	    return returnCallBackPage($client,itemRecommendAdd ); 
	 }
	 
	 
	 
	 
	 
/*************************************************end商品API***************************************************/ 
	/**
	 *  检查OS商品库存是否等于TOP库存 
	 *  如果SKU库存明细相等 则不更新SKU,如果OS当商品库存大于TOP库存则更新
	 * */
	function Check_Update_SKU($iid){
		  global $db,$os;  
		  $sql="select * from open_tb_sku WHERE iid='".$iid."'";   //得到sku_ID
		  $rows = $db->getAll($sql);
		  foreach ($rows as $row){ 
		     if( $sku_id = $row['sku_id'] ) GetInsertIntoSKU( $sku_id );  //更新sku明细
		  }
		  
	} 
    /**
	 * 根据OS当中更新top的sku  上传库存。0库存则下架
	 * 再次完善top上的已有库存本地没有的问题(测试驱动)
	 * */
	function TOP_Item_Update_SKU($iid){
		global $db,$os,$_CFG;  
		//if( ! Check_is_exist('tb_item','iid',$iid) )
		GetTBOneItem( $iid );//立马下载宝贝。后期可以优化   //props
		$old_props = Check_is_exist('tb_item','iid',$iid,'','props');
		$goods_sn = Check_is_exist('tb_item','iid',$iid,'','outer_id');
		$cid = Check_is_exist('tb_item','iid',$iid,'','cid');  
		UploadItemimg( $goods_sn, $iid,$cid,1);    //上传商品图片相册   
		$sql="select g.*,(select ifnull(sum(gi.goods_number_available),0) from open_goods_inventory as gi where gi.goods_id = g.goods_id ) as t_num 
			 from open_goods as g where g.goods_sn= '".$goods_sn."'"  ;    //正确的库存  可用库存  25件  
		$row = $db->getRow($sql); 
		if( !$row ) return ;//库存中没有商品则返回
		$sku_properties='';
		$sku_quantities='';
		$sku_prices='';
		$sku_outer_ids='';     
        $sql = "select gi.goods_id,gi.goods_number_available,gi.goods_number_presale,gi.onsell_num,g.goods_sn,g.goods_name,gi.goods_spec_price,g.shop_price,c.color_name,c.color_code, tb_gg1.color_code,tb_gg1.pid as gg1_pid, tb_gg1.vid as gg1_vid, s.size_name, s.size_code, tb_gg2.size_code as gg2_size_code ,tb_gg2.pid as gg2_pid, tb_gg2.vid as gg2_vid 
			from open_goods_inventory as gi left join open_goods as g on gi.goods_id = g.goods_id 
			left join open_color as c on gi.color_id = c.color_id 
			left join open_size as s on gi.size_id = s.size_id 
			left join open_tb_guige1 as tb_gg1 on ( tb_gg1.color_code = c.color_code  ) and tb_gg1.cid= ".$cid." 
			left join open_tb_guige2 as tb_gg2 on (tb_gg2.size_code =s.size_code  ) and tb_gg2.cid= ".$cid." 
			where g.goods_sn='".$goods_sn."' order by tb_gg2.size_code " ;  
 	   $res = $db->query($sql); 
	   $i = 0;	
		while ($row2 = $db->fetchRow($res)) {  
			if( !$row2['gg2_vid'] && (!$row2['size_code']=='00')) { 
				continue;
			}  
		   $row2['goods_spec_price'] = $row2['goods_spec_price'] ? $row2['goods_spec_price'] : $row2['shop_price'] ;
		   $sell_price= ($_CFG['detail_dif_price']==1) ? $row2['shop_price'] :$row2['goods_spec_price'];  //读配制取商品异价
		   if( $i > 18) break;  // 最多18个尺码 
		   if($sku_properties!=''){  //$props.';'.
				if($row2['gg1_vid'] && $row2['gg2_vid'])	$sku_properties = $sku_properties.','.$row2['gg1_pid'].':'.$row2['gg1_vid'].';'.$row2['gg2_pid'].':'.$row2['gg2_vid']; //颜色与尺码都存在
			 	if($row2['gg1_vid'] && !$row2['gg2_vid'])   $sku_properties = $sku_properties.','.$row2['gg1_pid'].':'.$row2['gg1_vid'];  //颜色存在但有此配件没有尺码
				if($row2['gg1_vid']){
					if( !strstr($old_props,$row2['gg1_pid'].':'.$row2['gg1_vid']) ) $old_props =$old_props.';'.$row2['gg1_pid'].':'.$row2['gg1_vid'] ;
				}
			 	if($row2['gg2_vid']){
					if( !strstr($old_props,$row2['gg2_pid'].':'.$row2['gg2_vid']) ) $old_props =$old_props.';'.$row2['gg2_pid'].':'.$row2['gg2_vid'] ;
				}
				/*******可用库存这里改成上架数 start*******/			
				$s_quantities = $row2['goods_number_available'];  //可用库存这里改成上架数
			 	$use_presale = $_CFG['use_presale']	; //是否启用商品预售:
			 	$use_onsell_num = $_CFG['use_onsell_num'] ; //是否启用商品上架数库存:
			 	$onsell_rate_num = $db->getOne("select onsell_rate_num from open_tb_app where is_use=1")  ; 
				$onsell_min_num =  $db->getOne("select onsell_min_num from open_tb_app where is_use=1")  ; 
			 	if( $use_presale ){ //启用
					$goods_allsell_num = goods_number_available + goods_number_presale ; //可售总库存 
			 	}else { //未启用
			 		$goods_allsell_num = goods_number_available ;  //可售总库存 
			 	}
			 	if( $use_onsell_num  ){ //是否启用商品上架数库存
			 		$s_quantities = $row2['onsell_num'] ; 
			 		if(!$s_quantities ) $s_quantities = $goods_allsell_num ; 
			 	} else {
			 		$s_quantities = $goods_allsell_num ; 
			 	} 
				/*******可用库存这里改成上架数 end*******/					 	
			 	if( $s_quantities && $s_quantities >0 ){
			 		$sku_quantities = $sku_quantities.','.$s_quantities  ;
			 	}else {
			 		$sku_quantities = $sku_quantities.','.'0'  ;
			 	} 
			 	$sku_prices = $sku_prices.','.$sell_price;
			 	$sku_outer_ids =$sku_outer_ids.",".$goods_sn ;  
			}else {
				if($row2['gg1_vid'] && $row2['gg2_vid'])  $sku_properties =  $sku_properties.$row2['gg1_pid'].':'.$row2['gg1_vid'].';'.$row2['gg2_pid'].':'.$row2['gg2_vid']; 
				if($row2['gg1_vid'] && !$row2['gg2_vid']) $sku_properties =  $sku_properties.$row2['gg1_pid'].':'.$row2['gg1_vid'] ; 
		        /*******可用库存这里改成上架数*******/			
				$s_quantities = $row2['goods_number_available'];  //可用库存这里改成上架数
			 	$use_presale = $_CFG['use_presale']	; //是否启用商品预售:
			 	$use_onsell_num = $_CFG['use_onsell_num'] ; //是否启用商品上架数库存:
			 	$onsell_rate_num = $db->getOne("select onsell_rate_num from open_tb_app where is_use=1")  ; 
				$onsell_min_num =  $db->getOne("select onsell_min_num from open_tb_app where is_use=1")  ; 
			 	if( $use_presale ){ //启用
					$goods_allsell_num = goods_number_available + goods_number_presale ; //可售总库存 
			 	}else { //未启用
			 		$goods_allsell_num = goods_number_available ;  //可售总库存 
			 	}
			 	if( $use_onsell_num  ){ //是否启用商品上架数库存
			 		$s_quantities = $row2['onsell_num'] ; 
			 		if(!$s_quantities ) $s_quantities = $goods_allsell_num ; 
			 	} else {
			 		$s_quantities = $goods_allsell_num ; 
			 	} 
				/*******可用库存这里改成上架数*******/	
				if( $s_quantities && $s_quantities >0 ){
					$sku_quantities = $sku_quantities.$s_quantities  ;
				}else {
					$sku_quantities = $sku_quantities.'0'  ;
				} 
			 	$sku_prices = $sku_prices.$sell_price ;
			 	$sku_outer_ids =$sku_outer_ids.$goods_sn ;  
			}   
		}	 
		$desc = '  商品描述 :'. $row['goods_brief'].$row['goods_desc'] ;    //测试
		$desc = ( str_len( trim( str_replace( " ",'', $desc)   ) ) > 15 ) ? $desc :  '  商品描述 :' ;   
			
	   /******宝贝标题begin*******/
	 	$goods_name = $row['goods_name'];
        $goods_sn = $row['goods_sn'];
        $goods_number = $row['goods_number'];
        $goods_weight = $row['goods_weight'];
        $market_price = $row['market_price'];
        $shop_price = $row['shop_price'];	 	
	 	$sql_bbname = "SELECT `bbnamestr` FROM " . $os->table('tb_app') . " WHERE `is_use` = 1";
	 	$res_bbname = $db->query($sql_bbname);
	 	while ($row_bbname = $db->fetchRow($res_bbname)){  
	 	    $bbnamestr = $row_bbname['bbnamestr'];
	 	}
	 	$bbname = "$bbnamestr";
	 /******宝贝标题end********/
	 	
		$userParamArr =array( 
					'title'	=> $goods_name, //宝贝标题。不能超过60字节，受违禁词控制 
					'desc' 	=> $desc ,  //宝贝描述。字数要大于5个字符，小于25000个字符，受违禁词控制 
					'image' 	=>'./../sources/'.$row['original_img'] ,  //商品主图片。类型:JPG,GIF;最大长度:500K 
					'num'    => $row['t_num'], //商品数量，取值范围:大于零的整数。数量需要等于SKU所有数量的和 
					'price'  => $row['shop_price'], //商品价格。取值范围:0-100000000;精确到2位小数;单位:元。如:200.07，表示:200元7分。需要在正确的价格区间内。 
			 		'iid' => $iid, //添加IID   
				);      
		if($sku_properties)  $userParamArr['sku_properties']= $sku_properties;
		if($sku_quantities)  $userParamArr['sku_quantities'] = $sku_quantities;  
		if($sku_prices)     $userParamArr['sku_prices']= $sku_prices;
		if($old_props)     $userParamArr['props']= $old_props; 
		if($sku_outer_ids)  $userParamArr['sku_outer_ids']= $sku_outer_ids ; 
		if($iid && $sku_properties && $sku_quantities ){
			echo ($goods_sn."此商品已经在".$cid.'已经存在!,正在[TOP_ItemUpdate] [更新库存]!  请等待....<br/>'); 
		    $result = TOP_ItemUpdate( $userParamArr );  
		    if($result[code]){//写出错日志 
				 print_r($userParamArr);
		    	 echo ($goods_sn.'TOP_ItemUpdate方法请求失败!'.':['.$result[code].']'.$result[msg] . ' <a herf="#" onclick="history.go(-1)">返回</a>');  
		    	// return $result;
		     }else { 
		         echo ('商品'.$goods_sn.'库存['.$sku_properties.']<br/>数量:'.$sku_quantities .'更新成功'. ' <a href="#" onclick="history.go(-1)">返回</a><br/>');  
				 UploadPropimg( $goods_sn, $iid,$cid,1 ) ;  //商品上传颜色属性图片 商品ID  与taobao的IID  
		     }	 
		}  
	} 
	/**
	 * 插入baobei商品
	 * */
	function InsertIntoTB_Goods($goods,$is_all='')	{    
		   if( is_array($goods)){
			   	$goods['item_desc'] = $goods['desc'] ;  //赋予商品描述
				$goods['location']   =  $goods['location']['city'].';'.$goods['location']['state']; //商品所在地   
		    	OS_InsertIntoTB('tb_item','iid',$goods); 
		   }   
		    /****属性中颜色与尺码自动关联***/
		    AutoExeGuige( $goods['outer_id'] ,addslashes($goods['property_alias']), $goods['cid'] ); //属性中颜色与尺码自动关联 
		    /****属性中颜色与尺码自动关联***/
		    /******分别插入商品的相关明细表信息******/
			if(  $goods['itemimgs'] ) {//插入ItemImg 表信息
				$ItemImgs =   $goods['itemimgs']   ; 
				InsertIntoTB_ItemImg_ByArray( $ItemImgs['itemimg'] ,  $goods['iid']); //插入ItemImg 表信息
			}    
			if( $goods['propimgs'] ) {//插入PropImg 表信息
				$propimgs =   $goods['propimgs']   ; 
				InsertIntoTB_PropImg_ByArray( $propimgs['propimg'] ,  $goods['iid']); //插入PropImg 表信息
			} 
		   if( $goods['skus'] ) {//skus 表信息
				$skus =   $goods['skus']   ;  
				InsertIntoTB_sku_ByArray( $skus['sku'],  $goods['iid'] ); //插入PropImg 表信息
			}
			if( $goods['videos'] ) {//videos 表信息
				$videos =   $goods['videos']   ; 
				InsertIntoTB_video_ByArray( $videos['$ideo'],  $goods['iid']  ); //插入PropImg 表信息
			}  
			/*****如果商品信息不全;则说明是批量下载 然而再调用得到单个商品详细信息*******/
		    if( !$goods['skus'] && !$goods['itemimgs'] && $is_all) GetTBOneItem( $goods['iid'] );  //得到单个商品详细信息 即没图片又没库存则单个信息获取
	} 
	/**
	 * taobao.item.get :得到单个商品信息 [查]
	 * 得到单个商品信息 并插入数据库
	 * */
	function  GetTBOneItem( $iid ){ 
	    $userParamArr = array(
				'fields' =>'iid,detail_url,num_iid,title,nick,type,cid,seller_cids,props,input_pids,input_str,desc,pic_path,num,
							valid_thru,list_time,delist_time,stuff_status,location,price,post_fee,express_fee,ems_fee,has_discount,
							freight_payer,has_invoice,has_warranty,has_showcase,modified,increment,auto_repost,approve_status,
							postage_id,product_id, auction_point,property_alias,itemimg, propimg, sku,outer_id,is_virtural,is_taobao,
							is_ex,video',  
				'iid' =>$iid , 
	     	);     
        $result = TOP_ItemGet( $userParamArr ) ;   
		InsertIntoTB_Goods( $result['item'] );//下载单个的goods   
	} 
	/**
	 * 根据外部goods_sn得到宝贝信息
	 * */
	function GetItemsCustomByOuter_id( $goods_sn ){
		$userParamArr = array(
				'fields' =>'iid,detail_url,num_iid,title,nick,type,cid,seller_cids,props,input_pids,input_str,desc,pic_path,num,
							valid_thru,list_time,delist_time,stuff_status,location,price,post_fee,express_fee,ems_fee,has_discount,
							freight_payer,has_invoice,has_warranty,has_showcase,modified,increment,auto_repost,approve_status,
							postage_id,product_id, auction_point,property_alias,itemimg, propimg, sku,outer_id,is_virtural,is_taobao,
							is_ex,video',  
				'outer_id' =>$goods_sn , 
	     	);  
	     $result = TOP_ItemsCustomGet( $userParamArr ) ;   
 	     if( $result['item']) { 
	     	if($result['item'][1])	{
	     		InsertIntoTB_Goods( $result['item'][0] );//下载单个的goods 
	     		if($result['item'][0]['iid']) return $result['item'][0]; 	 
	     	}else {
	     		InsertIntoTB_Goods( $result['item'] );
	     		if($result['item']['iid']) return $result['item']; 	   
	     	}
	     }
	}
	/**
	 * 得到单个应用的上架数量
	 * 根据配制
	 * */
	function Get_Onsell_Num_By_App($app){
 
	}
	/**
	 * taobao.item.add :添加一个商品   [卖] 先添加一个产品 
	 * 商品上传功能  商品代码。所属类目
	 * */
	function UpLoadGoods( $goods_sn, $GoodsParamArr  ){   
		global  $_CFG,$exc,$db,$os;   
		$result = GetItemsCustomByOuter_id( $goods_sn ) ; //得到最新的TOP item数据  
		$o_iid =$result['iid']; 
		$cid =  $GoodsParamArr['cid'];
		$str_props="";
		$o_props=$result['props']; 
		if($o_props){
			$str_arr = explode(';',$o_props);
			foreach ($str_arr as $str_prop ){
				$str_arr_props = explode(':',$str_prop);
				if($str_arr_props[0] !=$db->getOne("select pid from open_tb_guige1 where cid='".$cid."'") && $str_arr_props[0]!=$db->getOne("select pid from open_tb_guige2 where cid='".$cid."'") ){
					if($str_props!=''){
		    	   	   		$str_props=$str_props.';'.$str_arr_props[0] .':'.$str_arr_props[1]   ;
		    	   	   }else {
		    	   	   		$str_props=$str_props.$str_arr_props[0].':'.$str_arr_props[1] ;
		    	   	   }  
				}
			} 
		} 
		//$props=$str_props;  //将品牌放入属性串中 
		$props = str_replace("20000:135284;",'',$str_props ); //将品牌放入自定义串中 
		if(!Check_is_exist('tb_itemcat','cid',$cid) ) GetItemPropsByCid($cid); 
		$sql="select g.*,(select ifnull(sum(gi.goods_number_available),1) from open_goods_inventory as gi where gi.goods_id = g.goods_id ) as t_num 
			 from open_goods as g where g.goods_sn= '".$goods_sn."'"  ;    //正确的库存  可用库存  25件
		$row = $db->getRow($sql); 
		if( !$row ) return ;//库存中没有商品则返回
		/** 求出 颜色 尺码 属性的值 **/ 
	   if(!Check_is_exist('tb_guige1','spdm',$goods_sn, "cid='".$cid."'" ) ){// 扩展颜色 检查不存的 复制规格颜色信息
			$sql="insert into open_tb_guige1(cid,pid,prop_name,vid,name,name_alias,is_parent,status,sort_order,color_code,field1,field2,spdm) 
				 select cid,pid,prop_name,vid,name,name_alias,is_parent,status,sort_order,'','','','".$goods_sn."' from open_tb_guige1 
				 where cid='".$cid."' and (spdm is null or spdm='')";  
			$db->query($sql); 
		}
		$sql = "select DISTINCT(gi.color_id),gi.goods_id,c.color_code,c.color_name,tb_gg1.id,tb_gg1.cid,tb_gg1.pid,tb_gg1.vid,tb_gg1.name  
				from open_goods_inventory as gi 
				left join open_goods_color as gc on gi.color_id =gc.color_id and gi.goods_id =gc.goods_id  
				left join open_goods as g on g.goods_id=gc.goods_id 
				left join open_color as c on c.color_id=gc.color_id
				left join open_tb_guige1 as tb_gg1 on (tb_gg1.color_code = c.color_code and tb_gg1.spdm= g.goods_sn) and cid=".$cid." 
				where g.goods_sn = '".$goods_sn."'" ;  //颜色  一共有几个 颜色   
	    $res = $db->query($sql);  
	    while ($color_row = $db->fetchRow($res)){  
	    	   if($color_row['pid'] && $color_row['vid'] && $color_row['id'] ){
	    	   		  Update_table_key('tb_guige1','color_code',$color_row[color_code],"id='".$color_row['id']."'" ); // 更新并设置关联  
		    	   	   if($props!=''){
		    	   	   		$props=$props.';'.$color_row['pid'] .':'.$color_row['vid']   ;
		    	   	   }else {
		    	   	   		$props=$props.$color_row['pid'] .':'.$color_row['vid']  ;
		    	   	   } 
		    	   	   if ( $property_alias !=''){ //自定义属性名称跟商城名称相同
			    			 $property_alias=$property_alias.';'.$color_row['pid'].':'.$color_row['vid'].':'.$color_row['color_name'];
			    		}else {
			    			$property_alias=$property_alias.$color_row['pid'].':'.$color_row['vid'].':'.$color_row['color_name'];
			    		} 
	    	   }else { //系统自动维持颜色档案并记录 	1627207:3232483:半漂粉红条纹 
		    	   $sql_color="select * from open_tb_guige1 where cid='".$cid."' and (color_code='' or color_code is null) and spdm='".$goods_sn."' ";  //得到guige1表 没有关联颜色的ID 
				   if(!$guige1_row = $db->getRow($sql_color)) { //得到第一行  没有关联颜色记录
							echo ($goods_sn.":".$color_row['color_name'].'['.$color_row['color_code'].']' .'没有匹配到类目:'.$cid .'<br/>' ) ;  //得到一行没有关联颜色记录  
							continue;
						}  						
	  				Update_table_key('tb_guige1','color_code',$color_row[color_code],"id='".$guige1_row['Id']."'" ); // 更新并设置关联  
					if($props!=''){
						$props=$props.';'.$guige1_row['pid'] .':'.$guige1_row['vid']   ;
					}else {
						$props=$props.$guige1_row['pid'] .':'.$guige1_row['vid']  ;
					}  
		    	    if ( $property_alias !=''){ // //自定义属性名称跟商城名称相同
		    			 $property_alias=$property_alias.';'.$guige1_row['pid'].':'.$guige1_row['vid'].':'.$color_row['color_name'];
		    		}else {
		    			$property_alias=$property_alias.$guige1_row['pid'].':'.$guige1_row['vid'].':'.$color_row['color_name'];
		    		}  
	    	   } 
		}  
		if( !Check_is_exist('tb_guige2','spdm',$goods_sn, "cid='".$cid."'" ) ){//检查不存的 复制规格信息
			$sql="insert into open_tb_guige2(cid,pid,prop_name,vid,name,name_alias,is_parent,status,sort_order,size_code,field1,field2,spdm) 
				 select cid,pid,prop_name,vid,name,name_alias,is_parent,status,sort_order,'','','','".$goods_sn."' from open_tb_guige2 
				 where cid='".$cid."' and spdm is null";  
			$db->query($sql); 
		}
	    $sql="select DISTINCT(gi.size_id),gi.goods_id,s.size_name,s.size_code,tb_gg2.id,tb_gg2.cid,tb_gg2.pid,tb_gg2.vid,tb_gg2.name  
	    		from open_goods_inventory as gi
	    	    left join open_goods_size as gs on gi.size_id =gs.size_id and gi.goods_id =gs.goods_id  
				left join open_goods as g on g.goods_id=gs.goods_id 
				left join open_size as s on s.size_id=gs.size_id
				left join open_tb_guige2 as tb_gg2 on ( tb_gg2.size_code = s.size_code and tb_gg2.spdm= g.goods_sn ) and cid=".$cid." 
				where g.goods_sn  = '".$goods_sn."'  order by size_code " ; //尺码    
	    $res = $db->query($sql);
	    while ($size_row = $db->fetchRow($res))  { 
	    	  // if($size_row['size_code']=='00') continue;  有些商品有没尺码的如:配件  以后加权限类目暂时不完善 原来给特步运动品牌配件设计的
	    	   if($size_row['pid'] && $size_row['vid'] && $size_row['id'] ){
	    	   	 	   Update_table_key('tb_guige2','size_code',$size_row[size_code]," id='".$size_row['id']."'" ); // 更新并设置关联  
		    	   	   if($props!=''){
		    	   	   		$props=$props.';'.$size_row['pid'] .':'.$size_row['vid'] ;
		    	   	   }else {
		    	   	   		$props=';'.$props.$size_row['pid'] .':'.$size_row['vid'] ;
		    	   	   } 
		    	   	   if ( $property_alias !=''){ //自定义属性名称跟商城名称相同
			    			 $property_alias=$property_alias.';'.$size_row['pid'].':'.$size_row['vid'].':'.$size_row['size_name'];
			    	   }else {
			    			$property_alias=$property_alias.$size_row['pid'].':'.$size_row['vid'].':'.$size_row['size_name'];
			    	   } 
	    	   }else { 
	    	   			$sql_size="select * from open_tb_guige2 where cid='".$cid."' and (size_code='' or size_code is null) and spdm='".$goods_sn."'  and name='".str_replace('码','',$size_row['size_name'])."'";
	    	   		    //这里加判断运动鞋 尺码 与 本地size_name对应 先用名称匹配 
	    	   		    if(!$guige2_row = $db->getRow($sql_size)) {
	    	   		    	$sql_size="select * from open_tb_guige2 where cid='".$cid."' and (size_code='' or size_code is null) and spdm='".$goods_sn."' ";  //得到guige2表 没有关联尺码的ID 
						    if(!$guige2_row_temp = $db->getRow($sql_size)) {
						    	echo ($goods_sn.":".$size_row['size_name'].'['.$size_row['size_code'].']' .'没有匹配到类目:'.$cid .'<br/>' ) ;  //得到一行没有关联颜色记录  
						    	continue;
						    }else{ 
								Update_table_key('tb_guige2','size_code',$size_row[size_code],"id='".$guige2_row_temp['Id']."'" ); // 更新并设置关联   
								if($props!=''){
									$props=$props.';'.$guige2_row_temp['pid'] .':'.$guige2_row_temp['vid'] ;
								 }else{
									$props=';'.$props.$guige2_row_temp['pid'] .':'.$guige2_row_temp['vid'] ;
								}
								if( $property_alias !=''){ // //自定义属性名称跟商城名称相同
									$property_alias=$property_alias.';'.$guige2_row_temp['pid'].':'.$guige2_row_temp['vid'].':'.$size_row['size_name'];
								}else{
									$property_alias=$property_alias.$guige2_row_temp['pid'].':'.$guige2_row_temp['vid'].':'.$size_row['size_name'];
								}
								continue;
							}  
	    	   		    } 						
						Update_table_key('tb_guige2','size_code',$size_row[size_code],"id='".$guige2_row['Id']."'" ); // 更新并设置关联   
					  	if($props!=''){
		    	   	   		$props=$props.';'.$guige2_row['pid'] .':'.$guige2_row['vid'] ;
		    	   	     }else{
		    	   	   		$props=';'.$props.$guige2_row['pid'] .':'.$guige2_row['vid'] ;
		    	   	    }
						if( $property_alias !=''){ // //自定义属性名称跟商城名称相同
							$property_alias=$property_alias.';'.$guige2_row['pid'].':'.$guige2_row['vid'].':'.$size_row['size_name'];
						}else{
							$property_alias=$property_alias.$guige2_row['pid'].':'.$guige2_row['vid'].':'.$size_row['size_name'];
						}
	    	   } 
		}   
		//die($props);
 		$desc ='  商品描述 :'. $row['goods_brief'].$row['goods_desc'] ;    //测试
 		$desc = ( str_len( trim( str_replace( " ",'', $desc)   ) ) > 15 ) ? $desc :  '  商品描述 :' ;  
//		$fp = fopen('./images/tmp.jpg', 'w+');   
//		if( $row['original_img'] ) fwrite($fp, file_get_contents( $GLOBALS['_CFG']['pre_fetch_img'].$row['original_img']   ));
//		fclose($fp);   
//	   if( $vid= Check_is_exist('tb_propvalue','vid',Check_is_exist('tb_brand','nick',API_USER,'','vid'),'','vid' ) ){  	//判断品牌是否在top属性值中定义过。大品牌都已经定义
//			$input_pids ="1632501";  //货号 
//			$input_str =$row['goods_sn']; //货号 
//			//把品牌放入固定属性当中 
//			if($props) {
//				$props =$props.";20000:".$vid;
//			}else {
//				$props =$props."20000:".$vid;
//			}
//		    $input_pids = '20000,1632501'  ; //'20000,1632501' ,  //,品牌，货号',
//			$input_str  = Check_is_exist('tb_brand','nick',API_USER,'','name').",".$row['goods_sn']  ; // $row['goods_sn']  , //."Check_is_exist('tb_brand','nick',API_USER,'','name').",
//	   }else {
		$brand = Check_is_exist('tb_brand','nick',API_USER,'','name');
		if( !$brand ) $brand="百胜01";
		if($cid==50010388){
	 		  $input_pids ='20000,1632501' ;     //,品牌，货号', '20000',  
			  $input_str  = $brand.';'.$brand.'系列;'.$row['goods_sn'].','.$row['goods_sn'] ;//Check_is_exist('tb_brand','nick',API_USER,'','name').";特步系列;".$row['goods_sn'].";货号;".$row['goods_sn']." ,".$row['goods_sn']  ; // $row['goods_sn']  , //."Check_is_exist('tb_brand','nick',API_USER,'','name').",
    	} else {	
    		 $input_pids = '20000,1632501'  ; //'20000,1632501' ,  //,品牌，货号',
    		 
			 $input_str  =$brand.",".$row['goods_sn']  ; // $row['goods_sn']  , //."Check_is_exist('tb_brand','nick',API_USER,'','name').",
	 	}
		 
//			$input_pids = '1632501';// '20000,1632501'  ; //'20000,1632501' ,  //,品牌，货号',
//			$input_str  = $row['goods_sn']  ; //Check_is_exist('tb_brand','nick',API_USER,'','name').",".$row['goods_sn']  ; // $row['goods_sn']  , //."Check_is_exist('tb_brand','nick',API_USER,'','name').",
			//'九牧王'.",".$row['goods_sn']  ;
			//	   } 
			
	   /******宝贝标题begin*******/
	 	$goods_name = $row['goods_name'];
        $goods_sn = $row['goods_sn'];
        $goods_number = $row['goods_number'];
        $goods_weight = $row['goods_weight'];
        $market_price = $row['market_price'];
        $shop_price = $row['shop_price'];	 	
	 	$sql_bbname = "SELECT `bbnamestr` FROM " . $os->table('tb_app') . " WHERE `is_use` = 1";
	 	$res_bbname = $db->query($sql_bbname);
	 	while ($row_bbname = $db->fetchRow($res_bbname)){  
	 	    $bbnamestr = $row_bbname['bbnamestr'];
	 	}
	 	//$bbname = "$bbnamestr";
	 	eval("\$bbname = \"$bbnamestr\";");	
	 /******宝贝标题end********/
	 	
	   $userParamArr =array(
				'num'    =>$row['t_num'], //商品数量，取值范围:大于零的整数。数量需要等于SKU所有数量的和 
				'price'  => $row['shop_price'], //商品价格。取值范围:0-100000000;精确到2位小数;单位:元。如:200.07，表示:200元7分。需要在正确的价格区间内。 
//				'type'   =>'fixed', //发布类型。可选值:fixed(一口价),auction(拍卖)。B商家不能发布拍卖商品，而且拍卖商品是没有SKU的 
				'stuff_status' => 'new', //新旧程度。可选值：new(新)，second(二手)，unused(闲置)。
				'title'	=> $bbname , //宝贝标题。不能超过60字节，受违禁词控制 
				'desc' 	=> $desc ,  //宝贝描述。字数要大于5个字符，小于25000个字符，受违禁词控制 
				'location.state'	=>$db->getOne("select ifnull(region_name,'浙江') from open_shop_config  as sc left join  open_region as r on r.region_id=sc.value where sc.code='shop_province'"),
				'location.city' 	=>$db->getOne("select ifnull(region_name,'杭州') from open_shop_config  as sc left join  open_region as r on r.region_id=sc.value where sc.code='shop_city'"),
				'approve_status' => $GoodsParamArr['approve_status'] ,//  'instock',  //商品上传后的状态。可选值:onsale(出售中),instock(仓库中);默认值:onsale 
				'cid' 	=> $cid ,
				'props' 	=> $props,   //商品属性列表。格式:pid:vid;pid:vid。
				'freight_payer' 	=>'buyer', //运费承担方式。可选值:seller（卖家承担）,buyer(买家承担);默认值:seller。
				'valid_thru' 	=>'7',  //有效期。可选值:7,14;单位:天;默认值:14 
				'has_invoice' 	=>'true', //是否有发票。可选值:true,false (商城卖家此字段必须为true);默认值:false(无发票) 
				'has_warranty' 	=>'false', //是否有保修。可选值:true,false;默认值:false(不保修) 
				'auto_repost'	=>'true',  //自动重发。可选值:true,false;默认值:false(不重发) 
				'has_showcase' 	=>'false',  //橱窗推荐。可选值:true,false;默认值:false(不推荐) 
// 				'seller_cids' 	=>'',  //商品所属的店铺类目列表。按逗号分隔。结构:",cid1,cid2,...,"，如果店铺类目存在二级类目，必须传入子类目cids。 
//				'has_discount' 	=>'false', //支持会员打折。可选值:true,false;默认值:false(不打折) 
//				'post_fee' 	=>'5',  //平邮费用。取值范围:0.01-10000.00;精确到2位小数;
//				'express_fee'	=>'6',  //快递费用。取值范围:0.01-10000.00;
//				'ems_fee'	=>'11',  //ems费用。
//				'list_time' 	=>'', //定时上架时间。(时间格式：yyyy-MM-dd HH:mm:ss) 
//				'increment' 	=>'', //加价幅度。如果为0，代表系统代理幅度 
				'image' 	=>'./../sources/'.$row['original_img'] ,  //商品主图片。类型:JPG,GIF;最大长度:500K 
//				'postage_id' 	=>Check_is_exist('tb_postage','nick',API_USER,'','postage_id'),  
				'auction_point'  =>'5', //商品的积分返点比例。如:5,表示:返点比例0.5%. 注意：返点比例必须是>0的整数，
			 	//'property_alias' => $property_alias, //属性值别名。如pid:vid:别名;pid1:vid1:别名1 ，其中：pid是属性id vid是属性值id。总长度不超过511字节 
				//'sku_properties'  =>$sku_properties, //格式:pid:vid;pid:vid。该字段内的销售属性也需要在props字段填写。sku的销售属性需要一同选取，如:颜色，尺寸。如果新增商品包含了sku，则此字段一定要传入。 
				//'sku_quantities' =>$sku_quantities, //SKU的数量串，结构如：num1,num2,num3 如：2,3 
			    //'sku_prices'  =>$sku_prices, //SKU的价格串，结构如：10.00,5.00,… 精确到2位小数;单位:元。如:200.07，表示:200元7分 
				//'sku_outer_ids' =>$sku_outer_ids ,
//				'lang'  =>'',
				'outer_id' =>$row['goods_sn'],
 				//'product_id'  =>'79306132',//棉衣:79900403  jack:79921025,79929742 //西裤 80210213  niuzai:80219717  xiuxian:80225210
//				'pic_path'     =>'', 
			);  
		$sku_properties='';
		$sku_quantities='';
		$sku_prices='';
		$sku_outer_ids=''; 
	    $sql = "select gi.goods_id,gi.goods_number_available,gi.goods_number_presale,gi.onsell_num,g.goods_sn,g.goods_name,gi.goods_spec_price,g.shop_price,c.color_name,c.color_code, tb_gg1.color_code,tb_gg1.pid as gg1_pid, tb_gg1.vid as gg1_vid, s.size_name, s.size_code, tb_gg2.size_code as gg2_size_code ,tb_gg2.pid as gg2_pid, tb_gg2.vid as gg2_vid 
			from open_goods_inventory as gi left join open_goods as g on gi.goods_id = g.goods_id 
			left join open_color as c on gi.color_id = c.color_id 
			left join open_size as s on gi.size_id = s.size_id 
			left join open_tb_guige1 as tb_gg1 on ( tb_gg1.color_code = c.color_code and tb_gg1.spdm = g.goods_sn  ) and tb_gg1.cid= ".$cid." 
			left join open_tb_guige2 as tb_gg2 on ( tb_gg2.spdm = g.goods_sn and tb_gg2.size_code =s.size_code  ) and tb_gg2.cid= ".$cid." 
			where g.goods_sn='".$goods_sn."' order by tb_gg2.size_code " ;   
	    $res = $db->query($sql); 
	    $i = 0;	
		while ($row2 = $db->fetchRow($res)) {  
			if( !$row2['gg2_vid'] && (!$row2['size_code']=='00')) continue;
			if( $i > 18) break;  // 最多18个尺码 
			$row2['goods_spec_price'] = $row2['goods_spec_price'] ? $row2['goods_spec_price'] : $row2['shop_price'] ;
			$sell_price= ($_CFG['detail_dif_price']==1) ? $row2['shop_price'] :$row2['goods_spec_price'];  //读配制取商品明细异价 
		    if($sku_properties!=''){  //$props.';'.
			    if($row2['gg1_vid'] && $row2['gg2_vid'])	$sku_properties = $sku_properties.','.$row2['gg1_pid'].':'.$row2['gg1_vid'].';'.$row2['gg2_pid'].':'.$row2['gg2_vid']; 
			 	if($row2['gg1_vid'] && !$row2['gg2_vid'])   $sku_properties = $sku_properties.','.$row2['gg1_pid'].':'.$row2['gg1_vid']; 
			 	//$s_quantities = $row['goods_number_available']=='-1'?'0':$row['goods_number_available'];
			 	$s_quantities = $row2['goods_number_available'] ;    //可用库存这里 改成 上架数
		        /*******可用库存这里改成上架数*******/			 
			 	$use_presale = $_CFG['use_presale']	; //是否启用商品预售:
			 	$use_onsell_num = $_CFG['use_onsell_num'] ; //是否启用商品上架数库存:
			 	$onsell_rate_num = $db->getOne("select onsell_rate_num from open_tb_app where is_use=1")  ; 
				$onsell_min_num =  $db->getOne("select onsell_min_num from open_tb_app where is_use=1")  ; 
			 	if( $use_presale ){ //启用
					$goods_allsell_num = goods_number_available + goods_number_presale ; //可售总库存 
			 	}else { //未启用
			 		$goods_allsell_num = goods_number_available ;  //可售总库存 
			 	}
			 	if( $use_onsell_num  ){ //是否启用商品上架数库存
			 		$s_quantities = $row2['onsell_num'] ; 
			 		if(!$s_quantities ) $s_quantities = $goods_allsell_num ; 
			 	} else {
			 		$s_quantities = $goods_allsell_num ; 
			 	} 
				/*******可用库存这里改成上架数*******/	
				
			 	// 是否启用商品预售:
			 	if($s_quantities && $s_quantities>0){
			 		$sku_quantities = $sku_quantities.','.$s_quantities  ;
			 	}else {
			 		$sku_quantities = $sku_quantities.','.'0'  ;
			 	} 
			 	$sku_prices = $sku_prices.','.$sell_price ;
			 	$sku_outer_ids =$sku_outer_ids.",".$goods_sn ; 
			}else {
				if($row2['gg1_vid'] && $row2['gg2_vid'])  $sku_properties =  $sku_properties.$row2['gg1_pid'].':'.$row2['gg1_vid'].';'.$row2['gg2_pid'].':'.$row2['gg2_vid']; 
				if($row2['gg1_vid'] && !$row2['gg2_vid']) $sku_properties =  $sku_properties.$row2['gg1_pid'].':'.$row2['gg1_vid'] ; 
		    	$s_quantities = $row2['goods_number_available'] ;   //可用库存这里改成上架数
		        /*******可用库存这里改成上架数*******/			 
			 	$use_presale = $_CFG['use_presale']	; //是否启用商品预售:
			 	$use_onsell_num = $_CFG['use_onsell_num'] ; //是否启用商品上架数库存:
			 	$onsell_rate_num = $db->getOne("select onsell_rate_num from open_tb_app where is_use=1")  ; 
				$onsell_min_num =  $db->getOne("select onsell_min_num from open_tb_app where is_use=1")  ; 
			 	if( $use_presale ){ //启用
					$goods_allsell_num = goods_number_available + goods_number_presale ; //可售总库存 
			 	}else { //未启用
			 		$goods_allsell_num = goods_number_available ;  //可售总库存 
			 	}
			 	if( $use_onsell_num  ){ //是否启用商品上架数库存
			 		$s_quantities = $row2['onsell_num'] ; 
			 		if(!$s_quantities ) $s_quantities = $goods_allsell_num ; 
			 	} else {
			 		$s_quantities = $goods_allsell_num ; 
			 	} 
				/*******可用库存这里改成上架数*******/	
				if($s_quantities && $s_quantities>0){
					$sku_quantities = $sku_quantities.$s_quantities  ;
				}else {
					$sku_quantities = $sku_quantities.'0'  ;
				} 
			 	$sku_prices = $sku_prices.$sell_price ;
			 	$sku_outer_ids =$sku_outer_ids.$goods_sn ; 
			}   
		}  
		if( $GoodsParamArr['type'] )  $userParamArr['type'] = $GoodsParamArr['type']; 
		if($sku_properties)  $userParamArr['sku_properties']= $sku_properties;
		if($sku_quantities)  $userParamArr['sku_quantities'] = $sku_quantities; 
		if($property_alias)  $userParamArr['property_alias'] = $property_alias; 
	    if($input_pids)  $userParamArr['input_pids'] = $input_pids; 	
		if($input_str)  $userParamArr['input_str'] = $input_str; 		
		if($sku_prices)     $userParamArr['sku_prices']= $sku_prices;
		if($sku_outer_ids)  $userParamArr['sku_outer_ids']= $sku_outer_ids ;
	    if($input_pids)  $userParamArr['input_pids'] = $input_pids; 	
		if($input_str)  $userParamArr['input_str'] = $input_str; 	 
		if($GoodsParamArr['seller_cids'])  $userParamArr['seller_cids']=$GoodsParamArr['seller_cids'];   //卖家类目, ,
        if($GoodsParamArr['post_fee'])  $userParamArr['post_fee']=$GoodsParamArr['post_fee'];
        if($GoodsParamArr['express_fee'])  $userParamArr['express_fee']=$GoodsParamArr['express_fee'];
        if($GoodsParamArr['ems_fee'])  $userParamArr['ems_fee']=$GoodsParamArr['ems_fee'];  
        if($GoodsParamArr['has_discount'])  $userParamArr['has_discount']=$GoodsParamArr['has_discount'];  //是否支持折扣
        if($GoodsParamArr['freight_payer'])  $userParamArr['freight_payer']=$GoodsParamArr['freight_payer'];  // //卖家承担不用设置邮费和postage_id.买家承担的时候，必填邮费和postage_id
        if($GoodsParamArr['postage_id'])  $userParamArr['postage_id']=$GoodsParamArr['postage_id']; 

        if( !$o_iid ){ //不存在 增  
  			  echo ($goods_sn.'此商品正在[TOP_ItemAdd][上传]!  请等待....<br/>'); 
  			  $result = TOP_ItemAdd( $userParamArr );	
  			  if(  $iid = $result['item']['iid']  ) {
  			  	  echo ('商品(['.$row["goods_sn"] .']'.$row["goods_name"] .') [上传]成功!<a href="#" onclick="history.go(-1)">返回</a><br/>' ) ;
			   }
  		}else { //此商品已经上传top 则更新
  			  $is_update = 1; 
  			  echo ($goods_sn."此商品已经在".$cid.'已经存在!,正在[TOP_ItemUpdate] [更新]!  请等待....<br/>'); 
  			  if($o_iid)   $userParamArr['iid'] = $o_iid;//添加IID   
  			 // print_r($userParamArr); 
  			  $result = TOP_ItemUpdate( $userParamArr );  
  			  if(($iid = $result['item']['iid']) && ( $o_iid == $iid) ){
  			  	   echo ('商品(['.$row["goods_sn"] .']'.$row["goods_name"] .')在'.$result['item']['modified'].'更新成功!<a href="#" onclick="history.go(-1)">返回</a><br/>' ) ;
  			  } 
  		} 
  	   
       if($result[code]){//提示出错  
       	    print_r($userParamArr);
			echo ("[".$goods_sn."]". $row['goods_name'] .": 执行出错:[".$result[code]."]".$result[msg].'<a href="#" onclick="history.go(-1)">返回</a><br/>');
    		return ;  //上传出错时返回
       }else {
//	       	UpLoadSKU( $row['goods_sn'], $iid,$cid,$is_update );		 //上传商品成功后调用  
			UploadPropimg( $row['goods_sn'], $iid,$cid,$is_update ) ;  //商品上传颜色属性图片 商品ID  与taobao的IID 
			UploadItemimg($row['goods_sn'], $iid,$cid ,$is_update);    //上传商品图片相册 
	    	GetTBOneItem( $iid );//立马下载宝贝。后期可以优化 	
       }   
		
	} 
	/**
	 * taobao.item.img.upload(添加商品图片)  [卖]
	 * 商品相册上传 商品ID  与taobao的IID
	 * */
	function UploadItemimg( $goods_sn, $iid , $cid ,$is_update='' ){ 
		global $db,$os ;  
		$sql = "select gg.*,g.goods_sn from open_goods_gallery as gg
				left join open_goods as g on g.goods_id =gg.goods_id
				where  gg.img_desc='' and g.goods_sn= '".$goods_sn."'" ;  //  
	    $res = $db->query($sql);    
	    if($is_update){
	    	$sql="select * from open_tb_itemimg where iid='".$iid."'";//删除已有的图片
			//echo $sql;
	    	$rows = $db->getAll($sql);
	    	foreach ($rows as $row){
		    		$userParamArr =array(
									'iid' =>$iid,
									'itemimg_id' => $row['itemimg_id'], //1 
						     ); 
					$result = TOP_ItemImgDelete($userParamArr);
					if($result[code]){
						echo ("商品".$itemimg_row[goods_sn]."相册：".$itemimg_row[img_id]."图片删除失败! : [".$result[code] ."]".$result[msg].'<a href="#" onclick="history.go(-1)">返回</a><br/>'); 
					}else {
						$sql="delete open_tb_itemimg from open_tb_itemimg where iid='".$iid."' and itemimg_id='".$row['itemimg_id']."'";
						$db->query($sql);
						echo ("商品".$itemimg_row[goods_sn]."相册：".$itemimg_row[img_id]."图片删除成功! ".'<a href="#" onclick="history.go(-1)">返回</a><br/>'); 
					}	 
	    	} 
	    }
	    while ($itemimg_row = $db->fetchRow($res)){   
		    	    $img_original = $itemimg_row['img_original'];
//		    	    die($img_original);//images/200912/754_P_1261004348174.jpg
//					$fp = fopen('./images/item_tmp.jpg', 'w+');     
//					$fp = fopen('./../sources/images/item_tmp.jpg', 'w+');   
//					fwrite($fp, file_get_contents( $GLOBALS['_CFG']['pre_fetch_img'].$img_original ) );
//					fclose($fp);   
					//if( filesize('./images/item_tmp.jpg') <= 0) continue ;   
					if( filesize('./../sources/'.$img_original) <= 0) continue ;  
					$userParamArr =array(
									'iid' => $iid,
									'image' => './../sources/'.$img_original, 
								); 
					//$result = TOP_ItemImgUpload($userParamArr);
					if($result[code]){//提示出错 
						//if( $result[code]  == '551') break ; //:商品图片不能超过5张
						//echo ("商品".$itemimg_row[goods_sn]."相册：".$itemimg_row[img_id]."图片上传失败! : [".$result[code] ."]".$result[msg].'<a href="#" onclick="history.go(-1)">返回</a><br/>'); 
						return ;  //上传出错时返回
					}else {
						//echo ("商品".$itemimg_row[goods_sn]."相册：".$itemimg_row[img_id]."图片上传成功!".'<a href="#" onclick="history.go(-1)">返回</a><br/>'); 
					} 
		    }     
	} 
	/**
	 * taobao.item.propimg.upload(添加或修改属性图片)   [卖]
	 * 商品上传颜色属性图片 商品ID  与taobao的IID 
	 * */
	function UploadPropimg( $goods_sn, $iid , $cid,$is_update=''  ){ 
		global $db,$os ;  
		/**删除原有的pro_img图片**/
		$sql="select iid,propimg_id,properties from open_tb_propimg  where iid='".$iid."'";
	    $res = $db->query($sql);
	    while ($old_propimg_row = $db->fetchRow($res)){ 
			$userParamArr = array(
							'propimg_id'  => $old_propimg_row['propimg_id'],  
							'iid' =>$iid,  
						);
			$result = TOP_ItemPropimgDelete($userParamArr);  //taobao.item.propimg.delete 
			if($result[code]){//提示出错 
				 echo ($goods_sn."商品,属性：".$old_propimg_row[properties]."图片删除失败!:[".$result[code]."]". $result[msg] ."<br/> "); 
			 }else {
			 	echo ($goods_sn."商品,属性：".$old_propimg_row[properties]."图片删除成功! <br/> ");   				 	
		     } 	
	    } 
	    $db->query("delete from open_tb_propimg  where iid='".$iid."'");		
		/**删除原有的pro_img图片**/   
		//$sql = " select gc.*,tb_gg1.cid,tb_gg1.pid,tb_gg1.vid,tb_gg1.name  from open_goods_color as gc 
		//		left join open_goods as g on g.goods_id=gc.goods_id 
		//		left join open_color as c on c.color_id=gc.color_id
		// 		left join open_tb_guige1 as tb_gg1 on (tb_gg1.color_code = c.color_code or tb_gg1.name =c.color_name) and cid=".$cid." 
		//		where g.goods_sn = '".$goods_sn."' group by color_name " ;  //颜色  
		$sql ="select  tb_gg1.cid,tb_gg1.pid,tb_gg1.vid,tb_gg1.name,c.color_name,c.color_code,c.color_id,g.goods_id,g.goods_name ,g.goods_sn 
			   from open_tb_guige1 as tb_gg1
			   left join open_color as c on  c.color_code=tb_gg1.color_code 
			   left join open_goods as g on tb_gg1.spdm=g.goods_sn
			   where tb_gg1.color_code<>'' and tb_gg1.spdm = '".$goods_sn."'";	 
	    $res = $db->query($sql);
	    while ($color_row = $db->fetchRow($res)){  
	    	   if($color_row['pid'] && $color_row['vid'] ){
	    	   			$props= $color_row['pid'] .':'.$color_row['vid']  ;  
	    	   			$sql="select img_original from open_goods_gallery where color_id='".$color_row['color_id']."' and goods_id='".$color_row['goods_id']."' order by sort_order asc"; 
 				  		if( !$img_original = $db->getOne($sql) ) continue ; //相删路径 
//						$fp = fopen('./images/prop_tmp.jpg', 'w+');   
//						fwrite($fp, file_get_contents( $GLOBALS['_CFG']['pre_fetch_img'].$img_original ) );
//						fclose($fp);  
//						if( filesize('./images/prop_tmp.jpg') <= 0) continue ;  
						if( filesize('./../sources/'.$img_original) <= 0) continue ;   
	   					$userParamArr =array(
	   									'iid' => $iid,
	   									'properties' => $props,
	   									'image' => './../sources/'.$img_original , 
	   								);  
	   					if(Check_is_exist('tb_propimg','iid',$iid,"properties='".$props."'")){ //更新
	   						 $result = TOP_ItemPropimgUpload($userParamArr); //相同涵数
	   						 if(!$result[code])  echo("商品[".$goods_sn."]颜色:".$color_row['color_name']."[更新]成功!<br/>") ;
	   					}else { //新增itmepropimg 
	   						 $result = TOP_ItemPropimgUpload($userParamArr);
							 //print_r( $result );
	   						 if(!$result[code])  echo($iid."商品[".$goods_sn."]颜色:".$color_row['color_name']."[新增]成功!<br/>");
	   					} 
	   					if($result[code]){//提示出错 
	   						print_r($userParamArr);
							echo ("<br/>商品".$color_row[goods_sn]."属性：".$color_row[color_name]."图片上传".$color_row[name].$color_row[vid]."失败!:[".$result[code]."]". $result[msg] ."<br/> "); 
							return ;  //上传出错时返回
						} 
	    	   }else {
	    	   		  echo ('先维护颜色档案:(['. $color_row['color_name'] .']'. $color_row['color_code'] .')===>'. $sql );
	    	   		  exit(); 
	    	   } 
		    } 
	} 
	/**
	 * taobao.item.sku.add :添加SKU    [卖]
	 * 商品SKU上传功能  商品ID  与taobao的IID
	 * */
	function UpLoadSKU( $goods_sn, $iid , $cid, $is_update='' ){ 
		global $db,$os ;  
		$sql = "select gi.goods_id,gi.goods_number_available,g.goods_sn,g.goods_name,gi.goods_spec_price,g.shop_price,c.color_name,c.color_code, tb_gg1.color_code,tb_gg1.pid as gg1_pid, tb_gg1.vid as gg1_vid, s.size_name, s.size_code, tb_gg2.size_code ,tb_gg2.pid as gg2_pid, tb_gg2.vid as gg2_vid 
				from open_goods_inventory as gi left join open_goods as g on gi.goods_id = g.goods_id 
				left join open_color as c on gi.color_id = c.color_id 
				left join open_size as s on gi.size_id = s.size_id 
				left join open_tb_guige1 as tb_gg1 on (tb_gg1.color_code = c.color_code or tb_gg1.name =c.color_name ) and tb_gg1.cid= ".$cid." 
				left join open_tb_guige2 as tb_gg2 on ( tb_gg2.spdm = g.goods_sn and tb_gg2.size_code =s.size_code  ) and tb_gg2.cid= ".$cid." 
				where g.goods_sn='".$goods_sn."' order by tb_gg2.size_code " ;   
			$res = $db->query($sql); 
		    $i = 0;	
			while ($row = $db->fetchRow($res)) {  
					if( !$row['gg2_vid'] ) continue;
					if( $i > 18) break;  // 最多18个尺码
				    $row['goods_spec_price'] = $row['goods_spec_price'] ? $row['goods_spec_price'] : $row['shop_price'] ;
					$sell_price = ($_CFG['detail_dif_price']==1) ? $row['shop_price'] :$row['goods_spec_price'];  //读配制取商品明细异价
					$properties = $row['gg1_pid'].':'.$row['gg1_vid'].';'.$row['gg2_pid'].':'.$row['gg2_vid']  ; 
					$userParamArr = array(  //API用户参数 
										'iid' => $iid ,
										'properties' => $properties ,  //   '1627207:28341;20509:28314',//  '1627207:130164;2067137:28318', //addslashes($properties)  ,"1627207:130164;20509:28314"
										'quantity'   => $row['goods_number_available'] ,
										'outer_id'   => $goods_sn,
										'price'  => $sell_price   
									);  
					if(Check_is_exist('tb_sku','iid',$iid,"properties='".$properties."'")){  //TOP已经存在此sku属性则更新
						$result = TOP_ItemSkuUpdate($userParamArr);//taobao.item.sku.update :更新SKU信息  
						if(!$result[code]) echo ("商品[".$row['goods_sn']."]颜色:".$row['color_name'].";尺码:".$row['size_name']."可用数量:".$row['goods_number_available'] ."[更新]成功!<br/>"); 
					}else { 
						$result = TOP_ItemSkuAdd($userParamArr);  //不存在新增一条记录 
						if(!$result[code]) echo ("商品[".$row['goods_sn']."]颜色:".$row['color_name'].";尺码:".$row['size_name']."可用数量:".$row['goods_number_available'] ."[新增]成功!<br/>"); 
					} 
					if($result[code]){//提示出错 
						 echo ('sku('. $iid .')上传失败:(['.$result['code'] .']'.$result['msg']).']<br/>';
					}else {
						$i=$i+1;
					}
		 }
		    
	} 
	/**
	 * 传入iid自动下架功能 
	 * */
	function TOP_Item_UpdateDelisting( $iid ){
		$userParamArr =array(
				'iid'  =>$iid, 
			 );
		 $result =TOP_ItemUpdateDelisting($userParamArr);	
		 if($result[code]){//提示出错 
				echo ("[".$iid."] :下架出错:[".$result[code]."]".$result[msg]."<br/>"); 
		 }else {
		  		echo ('商品成功下架! <a href="#" onclick="history.go(-1)">返回</a>');		
		 } 	  
	}
	/**
	 * 传入iid与num库存数量自动上架功能 
	 * */
	function TOP_Item_UpdateListing( $iid,$num ){
		$userParamArr =array(
					'iid'  => $iid, 
					'num'  => $num , 
			 );
		$result =TOP_ItemUpdateListing($userParamArr);
		if($result[code]){//提示出错 
			echo ("[".$iid."] :上架出错:[".$result[code]."]".$result[msg]."<br/>"); 
		}else {
			echo ('成功上架! <a href="#" onclick="history.go(-1)">返回</a>');//下载运费模板 
		}  
	} 
	/**
	 * taobao.item.sku.get :获取SKU  [查]
	 * 插入SKU表。商品存在
	 * */	
	function GetInsertIntoSKU( $sku_id ){ 
		if($sku_id){
			$userParamArr = array( 
					'fields'=>'sku_id,iid,properties,quantity,price,outer_id,created, modified,status',
					'sku_id'=>$sku_id 
	     	);  
			$result = TOP_ItemSkuGet( $userParamArr ); 
			if(is_array( $result['sku']) ) {
				    OS_InsertIntoTB('tb_sku','sku_id',$result['sku'] ); 
			} 
		} 
	}
	/**
	 * 根据商品IID得到所有SKU
	 * */
	function GetInsertIntoSKUByIid($iid){
		if($iid){
			$userParamArr = array( 
					'fields'=>'sku_id,iid,properties,quantity,price,outer_id,created, modified,status',
					'iids'=> $iid 
	     	);  
			$result =TOP_ItemSkusGet( $userParamArr ); 
//			print_r($result);
//			exit;
			if(is_array( $result['sku']) ) {
				    OS_InsertIntoTB('tb_sku','sku_id',$result['sku'] ); 
			} 
		} 
	}
	/**
	 * taobao.postages.get(获取卖家的运费模板)[卖]
	 * 
	 * */
	function GetPostAges(){  
		$userParamArr = array(  
						'fields' =>'postage_id,name,memo,created,modified,post_price,post_increase,
									express_price,express_increase,ems_price,ems_increase,postage_mode_list' 
		 			);  
		$result = TOP_PostagesGet($userParamArr);
		if(is_array( $result['postage']) ) {
			$result['postage']['nick'] = API_USER ;  
			OS_InsertIntoTB('tb_postage','postage_id',$result['postage'] ); 
		}
		echo ('运费模板下载成功! <a href="#" onclick="history.go(-1)">返回</a><br/>');//下载运费模板  
	}  
	 /**
	 * InsertIntoTB_ItemImg_ByArray 插入ItemImg表中
	 * */
	function  InsertIntoTB_ItemImg_ByArray( $ItemImgs,$iid ){   
		  if(is_array($ItemImgs) && $ItemImgs[0]){
				foreach ( $ItemImgs  as $result ){   
					  if( is_array($result) ){
						  	 $result['iid']=$iid ;
						  	 OS_InsertIntoTB('tb_ItemImg','itemimg_id',$result);
						  }
					} 
			 }else {
			 		$ItemImgs['iid']=$iid;
			 		 OS_InsertIntoTB('tb_ItemImg','itemimg_id',$ItemImgs);
			 }  
	}  
	/**
	 * InsertIntoTB_PropImg_ByArray 插入PropImg
	 * */
	function  InsertIntoTB_PropImg_ByArray( $PropImgs ,$iid){  
		  if(is_array($PropImgs) && $PropImgs[0]){ 
				foreach ( $PropImgs  as $result ){
					   if( is_array($result) ){
						  	 $result['iid']=$iid ;
						  	 OS_InsertIntoTB('tb_PropImg','propimg_id',$result);
						  } 
					} 
			 }else {
			 		$PropImgs['iid']=$iid;
			 		 OS_InsertIntoTB('tb_PropImg','propimg_id',$PropImgs);
			 } 
	} 
 
	/**
	 * InsertIntoTB_video_ByArray 插入video表中
	 * */
	function  InsertIntoTB_video_ByArray( $videos,$iid ){ 
		  if(is_array($videos) && $videos[0]){
				foreach ( $videos  as $result ){
						if( is_array($result) ){
						  	 $result['iid']=$iid ;
						  	 OS_InsertIntoTB('tb_video','video_id',$result);
						  }  
					} 
			 }else {
			 		 $videos['iid']=$iid;
			 		 OS_InsertIntoTB('tb_video','video_id',$videos);
			 }   
	} 
	
	/**
	 * InsertIntoTB_sku_ByArray 插入sku表中
	 * */
	function  InsertIntoTB_sku_ByArray( $skus,$iid ){ 
		  if(is_array($skus) && $skus[0]){
			  	foreach ( $skus  as $result ){ 
			  			if( is_array($result) ){
						  	 $result['iid']=$iid ;
						  	 OS_InsertIntoTB('tb_sku','sku_id',$result);
						  }  
					} 
		 	 }else {
			 		 $skus['iid']=$iid ;
					 OS_InsertIntoTB('tb_sku','sku_id',$skus);
			 }   
	}
		
?>